package app

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "strconv"
    "time"
)

var engine *gin.Engine

//初始化http服务
func initEngine(callback func(engine *gin.Engine)) {
    config := GetConfig()
    logger := GetLogger()

    //设置服务运行模式
    gin.SetMode(config.RunMode)
    gin.DefaultWriter = logger.Out
    gin.DefaultErrorWriter = logger.Out

    //创建一个新的路由引擎
    engine = gin.New()
    engine.Use(gin.Logger())
    callback(engine)

    engine.GET("/", func(c *gin.Context) { Json(c, NewRest().Msg("服务启动成功")) })
    engine.GET("/ping", func(c *gin.Context) { Json(c, NewRest().Msg(strconv.FormatInt(time.Now().Unix(), 10))) })
    engine.NoMethod(func(c *gin.Context) { Json(c, NewRest().Code(405).Msg("方法禁用")) })
    engine.NoRoute(func(c *gin.Context) { Json(c, NewRest().Code(404).Msg("资源不存在")) })
    for _, v := range config.StaticUrlMap {
        engine.Static(v[0], v[1])
    }
    go starupSuccess()
    //启动http服务
    _ = engine.Run(":" + strconv.Itoa(config.Port))
}

func GetEngine() *gin.Engine {
    return engine
}

func starupSuccess() {
    fmt.Printf("[GIN] %v |服务启动成功 | http://localhost:%d\n",
        time.Now().Format("2006/01/02 - 15:04:05"), config.Port)
}

//启动服务
func Startup(callback func(engine *gin.Engine)) {
    //1.初始化配置文件
    initConfig()
    //2.初始化日志
    initLogger()
    //3.初始化数据库
    initDatabase()
    //4.初始化服务器引擎
    initEngine(callback)
}
